package io.jee.caisan.weixin.service.impl;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import io.jee.alaska.util.Result;
import io.jee.caisan.member.client.model.RemoteMember;
import io.jee.caisan.member.client.service.RemoteBalanceService;
import io.jee.caisan.member.client.service.RemoteLevelService;
import io.jee.caisan.member.client.service.RemoteMemberService;
import io.jee.caisan.member.client.service.RemoteSignService;
import io.jee.caisan.member.domain.MemberBalance;
import io.jee.caisan.member.domain.MemberLevel;
import io.jee.caisan.weixin.config.UrlManager;
import io.jee.caisan.weixin.domain.Member;
import io.jee.caisan.weixin.domain.SysConfig;
import io.jee.caisan.weixin.repository.MemberRepository;
import io.jee.caisan.weixin.service.LogService;
import io.jee.caisan.weixin.service.MemberService;
import io.jee.caisan.weixin.service.SysConfigService;
import io.jee.caisan.weixin.vo.MemberVo;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;

@Service
@Transactional
public class MemberServiceImpl implements MemberService{
	
	@Resource
	private WxMpService wxService;
	
	@Resource
	private RemoteMemberService remoteMemberService;
	
	@Resource
	private RemoteBalanceService remoteBalanceService;
	
	@Resource
	private RemoteLevelService remoteLevelService;
	
	@Resource
	private RemoteSignService remoteSignService;
	
	@Resource
	private MemberRepository memberRepository;
	
	@Resource
	private LogService logService;
	
	@Resource
	private PasswordEncoder passwordEncoder;
	
	@Resource
	private UrlManager urlManager;
	
	@Resource
	private SysConfigService sysConfigService;
	
	@Override
	public MemberVo getMember(int mid) {
		Member member = memberRepository.findById(mid).orElse(null);
		if(member == null) {
			return null;
		}
		RemoteMember remoteMember = remoteMemberService.getRemoteMember(member.getMid());
		MemberBalance memberBalance = remoteBalanceService.getBalance(mid);
		MemberLevel memberLevel = remoteLevelService.getLevel(mid);
		MemberVo vo = new MemberVo();
		vo.setMid(member.getMid());
		vo.setMobile(remoteMember.getMobile());
		vo.setEmail(remoteMember.getEmail());
		vo.setOpenid(member.getOpenid());
		vo.setNickname(remoteMember.getNickname());
		vo.setCaidou(memberBalance.getCaidou());
		vo.setCredit(memberBalance.getCredit());
		vo.setExp(memberLevel.getExp());
		vo.setLevel(memberLevel.getLevel());
		return vo;
	}

	@Override
	public Member findByOpenid(String openid) {
		return memberRepository.select().where("openid", openid).end().unique();
	}
	
	@Override
	public Result<Member> binding(String username, String password, String openid) {
		RemoteMember remoteMember = remoteMemberService.getRemoteMemberByUsername(username);
		//验证主站账户是否有效
		if (remoteMember == null || !passwordEncoder.matches(password, remoteMember.getPassword())) {
			return Result.error("账号或者密码不正确");
		}
		Member member = memberRepository.findById(remoteMember.getMid()).orElse(null);
		if(member == null) {//若微信Member为空，则添加
			member = new Member();
			member.setMid(remoteMember.getMid());
			member.setOpenid(openid);
			memberRepository.save(member);
			return Result.success("恭喜您，绑定成功", member);
		} else {
			return Result.error("此账号已经绑定了微信");
		}
	}

	@Override
	public Result<Void> unbind(int mid) {
		Member member = memberRepository.findById(mid).orElse(null);
		memberRepository.delete(member);
		return Result.success();
	}

	@Override
	public Result<?> forgotPassword(String username, String password, String code) {
		return remoteMemberService.forgotPassword(username, password, code);
	}

	@Override
	public Result<?> register(String openid, String username, String password, String code, String regip) throws WxErrorException {
		Result<?> result = remoteMemberService.register(username, password, code, regip);
		if(result.isSuccess()) {
			result = binding(username, password, openid);
		}
		return result;
	}

	@Override
	public WxMpXmlOutMessage wxMpVerifyBind(WxMpXmlMessage wxMessage) {
		String openid = wxMessage.getFromUser();
		Member member = findByOpenid(openid);
		if(member == null) {
			String msg = "您尚未绑定彩伞\n\n请<a href='" + urlManager.login() + "'>点击这里</a>进行绑定操作";
			SysConfig config = sysConfigService.findOneByType(SysConfig.TYPE_1);
			if(config != null) {
				msg += "\n\n" + config.getContent();
			}
			return WxMpXmlOutMessage.TEXT().content(msg).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
		}
		return null;
	}

	@Override
	public WxMpXmlOutMessage wxMpClickSgin(WxMpXmlMessage wxMessage) {
		String openid = wxMessage.getFromUser();
		Member member = findByOpenid(openid);
		
		Result<?> result = remoteSignService.signWeixin(member.getMid());
		if(!result.isSuccess()) {
			String msg = "签到失败\n原因："+result.getMessage();
			return WxMpXmlOutMessage.TEXT().content(msg).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>) result.getData();
		String time = map.get("time").toString();
		String caidou = map.get("caidou").toString();
		String credit = map.get("credit").toString();
		String exp = map.get("exp").toString();
		
		StringBuffer description = new StringBuffer();
		description.append("签到时间：" + time);
		description.append("\n获得彩豆：" + caidou + " 颗");
		description.append("\n获得积分：" + credit + " 分");
		description.append("\n获得经验：" + exp + " EXP");
		SysConfig config = sysConfigService.findOneByType(SysConfig.TYPE_2);
		if(config != null) {
			description.append("\n\n"+config.getContent());
		}
		WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
		item.setTitle("恭喜您，签到成功");
		item.setDescription(description.toString());
		item.setUrl(urlManager.personal());
		return WxMpXmlOutMessage.NEWS().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).addArticle(item).build();
	}

}
